<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>宠物管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="30">
        <el-col :span="9">
          <el-input
            placeholder="请输入类别"
            v-model="queryInfo.query"
            clearable
            @clear="getPetList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getPetList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addPetDialogVisible = true">添加宠物</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 数据表格 -->
    <el-table :data="petlist" border stripe>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="type" label="名字"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="weight" label="重量"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <!-- <el-table-column prop="healthStatus" label="健康状态"></el-table-column> -->
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removePetById(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        >
    </el-pagination>
    <!-- 增加页面 -->
    <el-dialog
      title="添加宠物"
      :visible.sync="addPetDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
    <!-- 内容主体区 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
      <el-form-item label="宠物分类" prop="type">
          <el-cascader
            v-model="addForm.type"
            :options="catelist"
            :props="{ expandTrigger: 'hover',
                      label: 'name',
                      value: 'id',
                      children: 'children' }"
            @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="宠物名" prop="name">
        <el-input v-model="addForm.name"></el-input>
      </el-form-item>
      <el-form-item label="宠物年龄" prop="age">
        <el-input v-model="addForm.age"></el-input>
      </el-form-item>
      <el-form-item label="宠物图片" ptop="pictrue">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8888/pet/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-preview="handView"
            v-model="imageUrl">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
      </el-form-item>
      <el-form-item label="宠物重量" prop="weight">
        <el-input v-model="addForm.weight"></el-input>
      </el-form-item>
      <el-form-item label="宠物价格" prop="price">
        <el-input v-model="addForm.price"></el-input>
      </el-form-item>
      <el-form-item label="健康状态" prop="healthStatus">
        <el-input v-model="addForm.healthStatus"></el-input>
      </el-form-item>
    </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPet">确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改页面 -->
    <el-dialog
      title="修改宠物"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
        <el-form-item label="宠物分类" prop="type">
          <el-input v-model="editForm.type"></el-input>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="age">
          <el-input v-model="editForm.age"></el-input>
        </el-form-item>
        <el-form-item label="宠物重量" prop="weight">
          <el-input v-model="editForm.weight"></el-input>
        </el-form-item>
        <el-form-item label="宠物价格" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-input v-model="editForm.healthStatus"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPetInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      // 宠物数据
      petlist: [],
      total: 0,
      addPetDialogVisible: false,
      addForm: {
        type: '',
        name: '',
        pictrue: '',
        age: null,
        weight: null,
        price: null,
        healthStatus: ''
      },
      addFormRules: {
        type: [{ required: true, message: '请选择宠物类型', trigger: 'blur' }],
        age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
        weight: [{ required: true, message: '重量不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
        healthStatus: [{ required: true, message: '健康状态不能为空' },
                      { min: 2, max: 6, message: '健康状态为2~6字符', teigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {},
      imageUrl: '',
      catelist: []
    }
  },
  created() {
    this.getPetList()
    this.getCateList()
  },
  methods: {
    async getCateList() {
        const { data: res } = await this.$axios.get('/product-categories/selectProduct',
        { params: { type: 2 } })
        if (res.code !== 200) {
          return this.$message.error('获取商品分类数据失败')
        }
        this.catelist = res.data.prolist
      },
    // 获取宠物数据
    async getPetList() {
      const { data: res } = await this.$axios.get('/pet/search', {
        params: this.queryInfo
      })
      if (res.code !== 200) {
        return this.$message.error('获取宠物失败！ ')
      }
      this.petlist = res.data.pet
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getPetList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getPetList()
    },
    // 监听修改会员对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听添加会员对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 宠物图片
    handleAvatarSuccess(res, file) {
      console.log('文件上传成功的钩子' + res)
        this.imageUrl = URL.createObjectURL(file.raw)
      },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 5

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 5MB!')
        }
        return isJPG && isLt2M
      },
      handView(file) {
        console.log(file)
        this.imageUrl = file.response.data.url
      },
    // 添加宠物方法
    addPet() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        const res = this.$axios.post('/pet/add', this.addForm)
        if (res.code !== 200) {
          this.$message.error('添加宠物失败')
        }
        this.$message.success('添加宠物成功')
        console.log(this.addForm)
        this.addPetDialogVisible = false
        this.getPetList()
        })
    },
    // 打开修改页面
    async showEditDialog(id) {
      console.log(id)
      // 通过ID查询到用户
      const { data: res } = await this.$axios.get('/pet/selectById/' + id)
      // 渲染到修改页面
      if (res.code !== 200) {
        return this.$message.error('查询失败！')
      }
      this.editForm = res.data.pet[0]
      this.editDialogVisible = true
    },
    // 修改事件
    editPetInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put('/pet/update/' + this.editForm.id, {
          type: this.editForm.type,
          age: this.editForm.age,
          weight: this.editForm.weight,
          price: this.editForm.price,
          healthStatus: this.editForm.healthStatus
        })
        if (res.code !== 200) {
          this.$message.error('更新失败！ ')
        }
        this.$message.success('更新成功！ ')
        this.getPetList()
        this.editDialogVisible = false
      })
    },
    async removePetById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该宠物，是否继续？', '删除宠物', {
            confirmButtonText: '',
            cancelButtonText: '',
            type: 'warning'
        }).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除 ')
            }
            const { data: res } = await this.$axios.delete('/pet/delete/' + id)
            if (res.code !== 200) {
                return this.$message.error('删除失败！ ')
            }
            this.$message.success('删除宠物成功！ ')
            this.getMenberlist()
    },
    handleChange(data) {
      console.log(data)
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
